<template>
  <div class="product-name-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="货物品名">
          <el-input v-model="searchForm.name" placeholder="请输入货物品名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>品名列表</span>
          <el-button type="primary" @click="handleAdd">新增品名</el-button>
        </div>
      </template>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" border>
        <el-table-column type="index" label="序号" width="80" :index="indexMethod" />
        <el-table-column prop="name" label="货物品名" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="修改时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 品名表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="100px"
      >
        <el-form-item label="货物品名" prop="name">
          <el-input v-model="productForm.name" placeholder="请输入货物品名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getProductNameList, 
  addProductName, 
  updateProductName, 
  deleteProductName 
} from '@/api/product'

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const productFormRef = ref()

// 品名表单
const productForm = reactive({
  id: '',
  name: ''
})

// 表单验证规则
const productRules = {
  name: [
    { required: true, message: '请输入货物品名', trigger: 'blur' }
  ]
}

// 获取品名列表
const getProductData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      name: searchForm.name
    }
    const response = await getProductNameList(params)
    tableData.value = response.records || response.data || []
    pagination.total = response.total || 0
  } catch (error) {
    console.error('获取品名列表失败:', error)
    ElMessage.error('获取品名列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getProductData()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  pagination.current = 1
  getProductData()
}

// 新增品名
const handleAdd = () => {
  dialogTitle.value = '新增品名'
  dialogVisible.value = true
  Object.assign(productForm, {
    id: '',
    name: ''
  })
}

// 编辑品名
const handleEdit = (row) => {
  dialogTitle.value = '编辑品名'
  dialogVisible.value = true
  Object.assign(productForm, {
    id: row.id,
    name: row.name
  })
}

// 删除品名
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该品名吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteProductName(row.id)
    ElMessage.success('删除成功')
    getProductData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await productFormRef.value.validate()
    
    // 准备提交数据
    const submitData = {
      name: productForm.name
    }
    
    if (productForm.id) {
      // 编辑模式，添加ID（保持字符串格式避免精度丢失）
      submitData.id = productForm.id
      console.log('提交的编辑数据:', submitData)
      await updateProductName(submitData)
      ElMessage.success('更新成功')
    } else {
      // 新增模式
      console.log('提交的新增数据:', submitData)
      await addProductName(submitData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    getProductData()
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

// 对话框关闭
const handleDialogClose = () => {
  productFormRef.value?.resetFields()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  getProductData()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  getProductData()
}

// 序号方法
const indexMethod = (index) => {
  return (pagination.current - 1) * pagination.size + index + 1
}

// 初始化
onMounted(() => {
  getProductData()
})
</script>

<style lang="scss" scoped>
.product-name-management {
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
    
    // 表格数据居中样式
    :deep(.el-table) {
      .el-table__cell {
        text-align: center !important;
      }
      
      .el-table__header {
        .el-table__cell {
          text-align: center !important;
        }
      }
    }
  }
}
</style> 